//
//  OASendApplyViewController.m
//  ERP
//
//  Created by goldeney on 15/3/19.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "OASendApplyViewController.h"

#import "GEDateTextField.h"
#import "GEPickerTextField.h"
#import "FileUploadModel.h"
#import "FileSizeFormatHelper.h"
#import "FileTypeIcon.h"
#import "GEObjectButton.h"
#import "GEInputTableViewCell.h"
#import "GEPickerTextField.h"

#import "ServiceConnect.h"
#import "UserLoginNSCoding.h"
#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

#import "OASendApplyNodeViewCell.h"

#import "UploadViewController.h"
#import "ThreeDataViewController.h"
#import "OASendApplyClassViewController.h"
#import "PreviewLocalFileHelper.h"

#import "OASendApplyHtmlViewController.h"

@interface OASendApplyViewController()

@property (nonatomic, strong) NSMutableArray *accessoryArray;
@property (nonatomic, assign) BOOL isUndertakes;

@property (nonatomic, strong) NSString *applyHtmlUrl;
@property (nonatomic, strong) NSMutableArray *appleNodeArray;

@end


@implementation OASendApplyViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"新建申请"];
        
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"继续" style:UIBarButtonItemStyleDone target:self
                                                                      action:@selector(uploadApplySelector:)];
        self.navigationItem.rightBarButtonItem = leftButton;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.accessoryArray = [NSMutableArray array];
    self.appleNodeArray = [NSMutableArray array];
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    
    //判断是否快速发起申请进入
    if(!self.value) return;
    [self backResultDataKey:@"ApplyModelClass" dataValue:self.value];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//添加文件
- (void)drawRowFileCell:(UITableViewCell*)cell model:(FileUploadModel *)model indexPath:(NSIndexPath *)indexPath
{
    CGSize cellSize = cell.frame.size;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, cellSize.height - 10, cellSize.height - 10)];
    imageView.image = [FileTypeIcon setFileTypeIcon:model.filePath];
    [cell.contentView addSubview:imageView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(cellSize.height + 5, 3, cellSize.width - cellSize.height - 60, cellSize.height/2)];
    titleLabel.text = model.fileName;
    titleLabel.font = [UIFont systemFontOfSize:15.0];
    titleLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:titleLabel];
    
    NSString *fileSize = [FileSizeFormatHelper getFileSizeString:[NSString stringWithFormat:@"%lld",model.fileSize]];
    UILabel *field = [[UILabel alloc] initWithFrame:CGRectMake(cellSize.height + 5, cellSize.height/2 - 2, cellSize.width - cellSize.height - 10, cellSize.height/2)];
    field.font = [UIFont systemFontOfSize:12.0];
    field.text = [NSString stringWithFormat:@"文件大小：%@", fileSize] ;
    field.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:field];
    
    GEObjectButton *button = [GEObjectButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(cellSize.width - 50, 0, cellSize.height, cellSize.height);
    [button setImage:[UIImage imageNamed:@"del.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(delFileSelector:) forControlEvents:UIControlEventTouchUpInside];
    button.object = @[@(indexPath.section), model];
    [cell.contentView addSubview:button];
    
    //添加分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 1, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [cell.contentView addSubview:lineView];
}

#pragma mark - UIAlertView

- (void)showAlertView:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}


#pragma mark
#pragma mark - 申请数据验证

- (void)uploadApplySelector:(id)selector
{
    //关闭键盘
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    //申请模板
    GEInputTableViewCell *applyCell = (GEInputTableViewCell*)[self.tableView getCellViewInRow:0 inSection:0];
    NSDictionary *appleModelDict = applyCell.tagData;
    
    //审批流程
    GEPickerTextField *field = [self.tableView getCellSaveClass:[GEPickerTextField class] pathForRow:1 inSection:0];
    NSDictionary *appleFlowDic = field.selectData;
    
    //代发机构
    UISwitch *switchs = [self.tableView getCellSaveClass:[UISwitch class] pathForRow:2 inSection:0];
    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:3 inSection:0];
    GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath1];
    NSDictionary *agencyDictionary = geViewCell.tagData;
    
    //编辑审批流程节点
    BOOL isFinishEdit = YES;
    if(self.appleNodeArray && self.appleNodeArray.count>0){
        for(NSDictionary *mDictionary in self.appleNodeArray){
            BOOL rankIdstatus = [[mDictionary objectForKey:@"rankIdstatus"] boolValue];
            NSInteger postid = [[mDictionary objectForKey:@"postid"] integerValue];
            if (rankIdstatus && postid == 0) isFinishEdit = NO;
        }
    }
    
    if (!(appleModelDict && appleModelDict.count>0)){
        [self showAlertView:@"请选择申请类型"];
    } else if (!(appleFlowDic && appleFlowDic.count>0)){
        [self showAlertView:@"请选择审批流程"];
    } else if (switchs.isOn && !agencyDictionary){
        [self showAlertView:@"请选择代发机构"];
    } else if (!(self.appleNodeArray && self.appleNodeArray.count>0)){
        [self showAlertView:@"没有找到审批节点，请选择审批流程"];
    } else if (!isFinishEdit){
        [self showAlertView:@"请\"编辑\"审批流程节点"];
    } else {
        //是否开启代发
        NSString *orgId = nil;
        NSString *deptId = nil;
        if (switchs.isOn) {
            orgId = [agencyDictionary objectFormatStringForKey:@"pId"];
            deptId = [agencyDictionary objectFormatStringForKey:@"id"];
        } else {
            UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
            orgId = userInfo.CorpId;
            deptId = userInfo.DeptId;
        }
        
        //数据集合
        NSMutableArray *data = [NSMutableArray array];
        [data addObject:orgId];//公司id
        [data addObject:deptId];//部门id
        [data addObject:[NSString stringWithFormat:@"%d",switchs.isOn]];//是否代发
        
        [data addObject:[appleModelDict objectFormatStringForKey:@"id"]];//模板id
        [data addObject:[appleFlowDic objectFormatStringForKey:@"id"]];//流程id
        
        [data addObject:self.appleNodeArray];//流程节点
        [data addObject:self.accessoryArray];//附件
        [data addObject:self.applyHtmlUrl];//模板地址
        
        OASendApplyHtmlViewController *viewController = [[OASendApplyHtmlViewController alloc] initWithValue:data];
        [self.navigationController pushViewController:viewController animated:YES];
    }
    
}

#pragma mark
#pragma mark - UISwitch Event

- (void)switchAction:(UISwitch*)switchs
{
    //申请模板
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    GEInputTableViewCell *applyCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
    NSDictionary *appleModelDict = applyCell.tagData;
    if(!appleModelDict) {
        [self showAlertView:@"请先选择申请类型"];
        switchs.on = NO; return;
    }
    
    self.isUndertakes = switchs.isOn;
    if (switchs.isOn) { //删除代发
        NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:3 inSection:0];
        NSArray *insertIndexPath = [NSArray arrayWithObjects:indexPath1, nil];
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:insertIndexPath withRowAnimation:UITableViewRowAnimationRight];
        [self.tableView endUpdates];
        
        //获取审批流程数据
        NSIndexPath *agencyIndexPath = [NSIndexPath indexPathForRow:3 inSection:0];
        GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:agencyIndexPath];
        if(geViewCell.tagData)[self getNetWorkNodeData];
        
    } else { //添加代发
        
        //获取审批流程数据
        NSIndexPath *agencyIndexPath = [NSIndexPath indexPathForRow:3 inSection:0];
        GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:agencyIndexPath];
        
        NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:3 inSection:0];
        NSArray *delIndexPath = [NSArray arrayWithObjects:indexPath1, nil];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:delIndexPath withRowAnimation:UITableViewRowAnimationLeft];
        [self.tableView endUpdates];
        
        //获取审批流程数据
        if(geViewCell && geViewCell.tagData) [self getNetWorkNodeData];
    }
}


#pragma mark
#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0) {
        return self.isUndertakes ? 4 : 3;
    } else if(section == 1) {
        return self.appleNodeArray.count>0 ? self.appleNodeArray.count : 1;
    } else if(section == 2) {
        return self.accessoryArray.count + 1;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"OAUploadBriefcaseViewCell%ld%ld",indexPath.section,indexPath.row];
    if(indexPath.section == 0){
        GEInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell != nil) return cell;
        
        //类型选择
        if(indexPath.row == 0){
            cell = [[GEInputTableViewCell alloc] initWithReuseIdentifier:CellIdentifier model:nil];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.titleName = @"申请类型";
            cell.placeholder = @"请选择申请类型";
            cell.isMark = YES;
            cell.isEdit = NO;
            [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
            
        } else if(indexPath.row == 1){
            //审批流程
            cell = [[GEInputTableViewCell alloc] initWithSelectReuseIdentifier:CellIdentifier model:nil];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.titleName = @"审批流程";
            cell.placeholder = @"请选择审批流程";
            cell.isMark = YES;
            [cell addDoneTarget:self action:@selector(textFieldDidChange:)];
            [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
            
        } else if(indexPath.row == 2){
            //是否代发
            cell = [[GEInputTableViewCell alloc] initWithSwitchReuseIdentifier:CellIdentifier target:self switchs:@selector(switchAction:)];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.titleName = @"是否代发";
            cell.isMark = NO;
            [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
            
        } else if(indexPath.row == 3){
            //机构数类型(1:公文机构职位树,2:消息管理机构职位树,3:通讯录关联公司列表树，4:代发机构)
            UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
            ServiceParametModel *model = [[ServiceParametModel alloc] init];
            model.methodName = @"OA_GetTree_Public";
            [model setValue:userInfo.Id forKey:@"userid"];
            [model setValue:@4 forKey:@"type"];
            
            //代发机构
            cell = [[GEInputTableViewCell alloc] initWithReuseIdentifier:CellIdentifier model:model];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.titleName = @"代发机构";
            cell.placeholder = @"请选择代发代发机构";
            cell.isMark = YES;
            cell.isEdit = NO;
            [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
        }
        
        return cell;
    }
    
    //审批流程
    else if(indexPath.section == 1){
        if (self.appleNodeArray.count <= 0) {
            GEInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) cell = [[GEInputTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            
            //移除其他控件
            for(UIView *view in cell.contentView.subviews){
                if([view isKindOfClass:[UIActivityIndicatorView class]]){
                    UIActivityIndicatorView *act = (UIActivityIndicatorView*)view;
                    [act stopAnimating];
                }
                [view removeFromSuperview];
            }
            
            if(cell.tag == -1) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 22.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                //act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(cell.tag == -2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"加载失败，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:14];
                label.textColor = [UIColor darkGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                
            } else if(cell.tag == -3){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"网络异常，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:14];
                label.textColor = [UIColor darkGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
            
        } else {
            OASendApplyNodeViewCell *cell = [[OASendApplyNodeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            //添加分割线
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 65, SuperWidth, 1)];
            lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            [cell.contentView addSubview:lineView];
            
            NSDictionary *mDictionary = [self.appleNodeArray objectAtIndex:indexPath.row];
            NSString *org = [mDictionary objectFormatForKey:@"org"];
            NSString *dept = [mDictionary objectFormatForKey:@"dept"];
            
            cell.compLable.text = org && ![org isEqualToString:@""] ? org : @"未知";
            cell.depLable.text = dept && ![dept isEqualToString:@""] ? dept : @"未知";
            cell.postLable.text = [mDictionary objectFormatStringForKey:@"tnodename"];
            cell.numberLable.text = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
            
            //节点是否修改消息
            NSDictionary *dictionary = [self.appleNodeArray objectAtIndex:indexPath.row];
            BOOL rankIdstatus = [[dictionary objectForKey:@"rankIdstatus"] boolValue];
            if (rankIdstatus) {
                cell.modifButton.hidden = NO;
                cell.selectionStyle = UITableViewCellSelectionStyleDefault;
                cell.incoBgLable.backgroundColor = [UIColor colorWithRed:255/255.0 green:128/255.0 blue:0/255.0 alpha:0.75];
                cell.incoTextLable.text = @"编辑节点";
            } else {
                cell.modifButton.hidden = YES;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
                
            return cell;
        }
    }
    
    //添加附件
    else if(indexPath.section == 2){
        GEInputTableViewCell *cell = [[GEInputTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.bounds = CGRectMake(0, 0, cell.bounds.size.width, 48);
        
        if (indexPath.row < self.accessoryArray.count) {
            FileUploadModel *model = [self.accessoryArray objectAtIndex:indexPath.row];
            [self drawRowFileCell:cell model:model indexPath:indexPath];
        } else {
            UIImage *image = [UIImage imageNamed:@"button_bg_add"];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.frame.size.width/2-image.size.width/2, cell.frame.size.height/2-image.size.height/2, image.size.width, image.size.height)];
            [imageView setImage:image];
            [cell.contentView addSubview:imageView];
        }
        return cell;
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //基本信息不添加
    if(section == 0) return nil;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor clearColor];
    
    UIView *viewBackground = [[UIView alloc] initWithFrame:CGRectMake(10, 0, SuperWidth - 20, 30)];
    viewBackground.backgroundColor = [UIColor whiteColor];
    [view addSubview:viewBackground];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SuperWidth - 30, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    if(section == 1){
        lable.text = @"审批流程";
    } else if(section == 2){
        lable.text = @"添加附件";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) return 0;
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1) return self.appleNodeArray.count>0 ? 66 : 44;
    if (indexPath.section == 2) return 48;
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //申请类型选择
    if(indexPath.section == 0 && indexPath.row == 0) {
        //GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        OASendApplyClassViewController *view = [[OASendApplyClassViewController alloc] init];
        view.key = @"ApplyModelClass";
        view.backResultDelagate = self;
        [self.navigationController pushViewController:view animated:YES];
    }
    
    //审批流程
    else if(indexPath.section == 0 && indexPath.row == 1) {
        NSIndexPath *indexPaths = [NSIndexPath indexPathForRow:0 inSection:0];
        GEInputTableViewCell *applyCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPaths];
        if(!applyCell.tagData) {
            [self showAlertView:@"请先选择申请类型"];
            return;
        }
        
        //获取数据
        GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        NSArray *resultArray = applyCell.objectData;
        if (resultArray) {
            NSDictionary *QDDJ = [NSDictionary dictionaryWithObject:@"%@" forKey:@"processName"];
            [geViewCell setPickerTextFieldComponents:resultArray keyValue:@[QDDJ]];
        }
    }
    
    //代发机构
    else if(indexPath.section == 0 && indexPath.row == 3){
        GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        NSArray *sendPeopleArray = geViewCell.objectData;
        
        if (sendPeopleArray) {
            ThreeDataViewController *view = [[ThreeDataViewController alloc] initWithStyle:SelectOne treeData:sendPeopleArray];
            view.backResultDelagate = self;
            [view setTitle:@"选择代发机构"];
            [view setTagKey:@"SendPeople"];
            [self.navigationController pushViewController:view animated:YES];
        } else {
            [geViewCell reloadData];
        }
        return;
    }
    
    //审批流程
    else if (indexPath.section == 1){
        GEInputTableViewCell *viewCell = (GEInputTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        if (indexPath.row == 0 && viewCell.tag != 0 && self.appleNodeArray.count <=0) { //重新获取数据
            [self getNetWorkNodeData];
        } else if(self.appleNodeArray.count>0){//数据节点修改/添加
            NSDictionary *dictionary = [self.appleNodeArray objectAtIndex:indexPath.row];
            NSInteger rankId = [[dictionary objectForKey:@"rankId"] integerValue];
            BOOL rankIdstatus = [[dictionary objectForKey:@"rankIdstatus"] boolValue];
            
            //添加节点消息
            if (rankIdstatus) {
                //机构数类型(1:公文机构职位树,2:消息管理机构职位树,3:通讯录关联公司列表树，4:申请，代发公司，部门查询调用接口,5: 发起申请节点修改树
                ServiceParametModel *model = [[ServiceParametModel alloc] init];
                model.methodName = @"OA_GetTree_Public";
                [model setValue:[NSNumber numberWithInteger:rankId] forKey:@"userid"];
                [model setValue:@5 forKey:@"type"];
                
                ThreeDataViewController *view = [[ThreeDataViewController alloc] initWithStyle:SelectOne serviceParamet:model];
                view.backResultDelagate = self;
                [view setTitle:@"选择审批节点"];
                [view setTagKey:@"NodePeople"];
                [view setSender:[NSNumber numberWithInteger:indexPath.row]];
                [self.navigationController pushViewController:view animated:YES];
            }
        }
    }
    
    //添加附件
    else if (indexPath.section == 2 && indexPath.row ==([self tableView:nil numberOfRowsInSection:2] - 1)) {
        UploadViewController *abstractView = [[UploadViewController alloc] init];
        [abstractView setNumberType:@"2" extension:nil];
        
        abstractView.key = @"AccessoryFile";
        abstractView.backResultDelagate = self;
        [self.navigationController pushViewController:abstractView animated:YES];
    }
    
    //附件预览
    else if (indexPath.section == 2){
        FileUploadModel *model = [self.accessoryArray objectAtIndex:indexPath.row];
        PreviewLocalFileHelper *preview = [PreviewLocalFileHelper instantiation];
        [preview previewViewController:self localFile:model.filePath];
    }
    
    //键盘事件处理
    if(indexPath.section == 0) {
        UITextField *textField = [self.tableView getCellSaveClass:[UITextField class] pathForRow:indexPath.row inSection:indexPath.section];
        if (textField) [textField becomeFirstResponder];
    }
    
}


#pragma mark -
#pragma mark Button Event

- (void)textFieldDidChange:(UITextField *)textField
{
    //获取节点信息
    [self getNetWorkNodeData];
}

- (void)delFileSelector:(GEObjectButton*)button
{
    NSArray *array = button.object;
    NSInteger section = [array[0] integerValue];
    id delValue = array[1];
    
    if (section == 2 && self.accessoryArray.count>0) {
        NSInteger index = [self.accessoryArray indexOfObject:delValue];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:2];
        
        NSArray *delIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.accessoryArray removeObject:delValue];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:delIndexPath withRowAnimation:UITableViewRowAnimationLeft];
        [self.tableView endUpdates];
    }
    
}

#pragma mark - NetWork

- (void)getNetWorkNodeData
{
    //申请模板
    NSIndexPath *indexPaths = [NSIndexPath indexPathForRow:0 inSection:0];
    GEInputTableViewCell *applyCells = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPaths];
    NSDictionary *appleModelDict = applyCells.tagData;
    
    GEPickerTextField *field = [self.tableView getCellSaveClass:[GEPickerTextField class] pathForRow:1 inSection:0];
    NSDictionary *appleFlowArray = field.selectData;
    id flowID = [appleFlowArray objectFormatForKey:@"id"];//流程ID
    id modelID = [appleModelDict objectFormatForKey:@"id"];//类型ID
    
    //判断有无数据，无数据就不显示任何控件
    if (!(flowID && modelID)) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
        GEInputTableViewCell *applyCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
        applyCell.tag = 0;
        NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
        return;
    }
    
    //代发人信息
    NSIndexPath *agencyIndexPath = [NSIndexPath indexPathForRow:3 inSection:0];
    GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:agencyIndexPath];
    NSDictionary *agencyDictionary = geViewCell.tagData;
    
    //是否开启代发
    UISwitch *switchs = [self.tableView getCellSaveClass:[UISwitch class] pathForRow:2 inSection:0];
    NSNumber *orgId = nil;
    NSNumber *deptId = nil;
    if (switchs.isOn) {
        orgId = [NSNumber numberWithInteger:[[agencyDictionary objectFormatIntegerNumberForKey:@"pId"] integerValue]];
        deptId = [NSNumber numberWithInteger:[[agencyDictionary objectFormatIntegerNumberForKey:@"id"] integerValue]];
    } else {
        UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
        orgId = [NSNumber numberWithInteger:[userInfo.CorpId integerValue]];
        deptId = [NSNumber numberWithInteger:[userInfo.DeptId integerValue]];
    }
    
    //清理所有数据
    [self.appleNodeArray removeAllObjects];
    NSIndexSet *sectionToReload = [[NSIndexSet alloc] initWithIndex:1];
    [self.tableView beginUpdates];
    [self.tableView reloadSections:sectionToReload withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
    
    //显示进度条
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    GEInputTableViewCell *applyCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
    applyCell.tag = -1;
    NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
    [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
    
    //获取数据
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:flowID forKey:@"processId"];
    [model setValue:modelID forKey:@"templateId"];
    [model setValue:orgId forKey:@"orgId"];
    [model setValue:deptId forKey:@"deptId"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_getNewApproval" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        if(result.resultArray && result.resultArray.count>0){
            NSArray *array = result.resultArray;
            [self.appleNodeArray addObjectsFromArray:array];
            
             NSIndexSet *sectionToReload = [[NSIndexSet alloc] initWithIndex:1];
             [self.tableView beginUpdates];
             [self.tableView reloadSections:sectionToReload withRowAnimation:UITableViewRowAnimationAutomatic];
             [self.tableView endUpdates];
        } else {
            applyCell.tag = -2;
            NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
            [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        applyCell.tag = -2;
        NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        applyCell.tag = -3;
        NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
    }];
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    [super backResultDataKey:key dataValue:backValue];
    NSArray *array = backValue;
    if (!(array && array.count>0)) return;
    
    if([key isEqualToString:@"ApplyModelClass"]){
        [self cleanAllData];//清理数据
        
        //申请模板
        NSArray *resultValue = backValue;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        GEInputTableViewCell *applyCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
        
        //申请类型返回
        NSDictionary *appleModelDict = [resultValue firstObject];
        applyCell.tagData = appleModelDict;
        applyCell.inputFiled = [appleModelDict objectFormatStringForKey:@"templatename"];
        
        //流程数据
        NSArray *resultData = [resultValue lastObject];
        applyCell.objectData = [resultData firstObject];
        
        //申请表模板地址
        NSDictionary *applyHtmlUrlDic = [((NSArray*)[resultData lastObject]) firstObject];
        self.applyHtmlUrl = [applyHtmlUrlDic objectFormatStringForKey:@"appurl"];
    }
    
    else if([key isEqualToString:@"SendPeople"]){
        //代发机构
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
        GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
        geViewCell.tagData = backValue;
        
        NSDictionary *mDictionary = backValue;
        NSMutableString *value = [NSMutableString string];
        [value appendFormat:@"%@",[mDictionary objectForKey:@"nodeName"], nil];
        
        UITextField *textField = [self.tableView getCellSaveClass:[UITextField class] pathForRow:3 inSection:0];
        textField.text = value;
        
        //获取网络数据
        [self getNetWorkNodeData];
    }
    
    else if([key isEqualToString:@"AccessoryFile"]){
        //添加附件
        if ([backValue isKindOfClass:[NSArray class]]) {
            NSMutableArray *insertIndexPath = [NSMutableArray array];
            for (int i=0;i<array.count;i++) {
                id value = [array objectAtIndex:i];
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:2];
                [insertIndexPath addObject:indexPath];
                [self.accessoryArray insertObject:value atIndex:0];
            }
            
            if (insertIndexPath.count>0) {
                [self.tableView beginUpdates];
                [self.tableView insertRowsAtIndexPaths:insertIndexPath withRowAnimation:UITableViewRowAnimationTop];
                [self.tableView endUpdates];
            }
        }
    }
}

- (void) backResultDataKey:(id)keyValue sender:(id)senderValue dataValue:(id)backValue
{
    [super backResultDataKey:keyValue sender:senderValue dataValue:backValue];
    if (!backValue) return;
    
    //节点数据添加
    if([keyValue isEqualToString:@"NodePeople"]){
        NSInteger row = [senderValue integerValue];
        NSDictionary *backDictionary = backValue;
        NSDictionary *mDictionary = [self.appleNodeArray objectAtIndex:row];
        
        NSMutableDictionary *addValueDictionary = [[NSMutableDictionary alloc] initWithDictionary:mDictionary];
        [addValueDictionary setObject:[backDictionary objectFormatStringForKey:@"name"] forKey:@"tnodename"];
        [addValueDictionary setObject:[backDictionary objectFormatStringForKey:@"orgname"] forKey:@"org"];
        [addValueDictionary setObject:[backDictionary objectFormatStringForKey:@"deptname"] forKey:@"dept"];
        [addValueDictionary setObject:[backDictionary objectFormatStringForKey:@"id"] forKey:@"postid"];
        [self.appleNodeArray setObject:addValueDictionary atIndexedSubscript:row];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:1];
        NSArray *insertIndexPath = @[indexPath];
        [self.tableView beginUpdates];
        [self.tableView reloadRowsAtIndexPaths:insertIndexPath withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];
    }
}

#pragma mark clean All Data

- (void)cleanAllData
{
    //清理页面数据
    NSIndexPath *indexPathTwo = [NSIndexPath indexPathForRow:1 inSection:0];
    GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPathTwo];
    geViewCell.objectData = nil;
    geViewCell.tagData = nil;
    geViewCell.inputFiled = @"";
    
    GEPickerTextField *field = [self.tableView getCellSaveClass:[GEPickerTextField class] pathForRow:1 inSection:0];
    field.selectData = nil;
    [field setComponents:nil keyValue:nil];
    
    NSIndexPath *indexPathOne = [NSIndexPath indexPathForRow:0 inSection:0];
    GEInputTableViewCell *geViewCellOne = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPathOne];
    geViewCellOne.objectData = nil;
    geViewCellOne.tagData = nil;
    geViewCellOne.inputFiled = @"";
    
    //清理流程页面数据
    NSIndexPath *indexPathss = [NSIndexPath indexPathForRow:0 inSection:1];
    GEInputTableViewCell *applyCellClean = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPathss];
    applyCellClean.tag = 0;
    NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPathss, nil];
    [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
    
    //清理流程所有数据
    self.applyHtmlUrl = nil;
    [self.appleNodeArray removeAllObjects];
    NSIndexSet *sectionToReload = [[NSIndexSet alloc] initWithIndex:1];
    [self.tableView beginUpdates];
    [self.tableView reloadSections:sectionToReload withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
}

@end
